package ar.edu.utn.behavior;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.util.List;

import ar.edu.utn.exceptions.ReflectionException;
import ar.edu.utn.injectors.Parameter;
import ar.edu.utn.xcontainer.Container;

public class ConstructorApplicator {
	
	public static boolean matchConstructor(Constructor constructor,
			List<Parameter> parameters) throws ReflectionException{

		Type[] types = constructor.getParameterTypes();
		if (types.length == parameters.size()) {

			for (int i = 0; i < parameters.size(); i++) {
				try{
					if (!types[i].equals(getType(parameters.get(i).getType()))) {
						return false;
					}
				}catch(ClassNotFoundException e){
					throw new ReflectionException("No se puedo encontrar la clase del parametro", e.getCause());
				}
				
			}
		} else {
			return false;
		}
		return true;
	}
	protected static Class<?> getType(String type) throws ClassNotFoundException{
		return Class.forName(type);
	}
	
	public static Object[] getconstructorArgValue(List<Parameter> parameters, Container container) throws ReflectionException{
		Object[] args=new Object[parameters.size()];
		for(int i=0;i<parameters.size();i++){
			Object value;
			if (parameters.get(i).getValue()==null){
				 value=container.getComponentInstance(getType(parameters.get(i).getType()));
			}else { value=args[i]=parameters.get(i).getValue();}
			args[i]=value;
		}
		return args;
		
	}

}
